<template>
  <el-menu
    :default-active="getSelected"
    class="el-menu-vertical-demo"
    @open="handleOpen"
    @close="handleClose"
    :unique-opened='true'
    :collapse="isCollapse"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
  >
    <h3>{{ isCollapse?'后台':'Fit后台管理系统' }}</h3>
    <el-menu-item
      @click="clickMenu(item)"
      v-for="item in noChildren"
      :key="item.name"
      :index="item.path"
    >
      <i :class="`el-icon-${item.icon}`"></i>
      <span slot="title">{{ item.label }}</span>
    </el-menu-item>
    <el-submenu v-for="item in hasChildren" :key="item.name" :index="item.name">
      <template slot="title">
        <i :class="`el-icon-${item.icon}`"></i>
        <span slot="title">{{ item.label }}</span>
      </template>
      <el-menu-item
        v-for="childItem in item.children"
        :key="childItem.name"
        :index="childItem.path"
        @click="clickMenu2(childItem,item)"
      >{{ childItem.label }}</el-menu-item>
    </el-submenu>
  </el-menu>
</template>

<script>
import { getMenusByRole } from '@/utils/permission';

export default {
  data() {
    return {
      menuData: []
    };
  },
  mounted() {
    // 根据用户角色加载菜单
    this.loadMenus();
  },
  methods: {
    // 加载菜单
    loadMenus() {
      this.menuData = getMenusByRole();
    },
    clickMenu(item) {
      if (
        this.$route.path === item.path ||
        (this.$route.path === "/home" && item.path === "/")
      ) {
        return;
      }
      this.$router.push(item.path);
      this.$store.commit('tab/setTabsList',item)
    },
    clickMenu2(item,parentItem){
      if (
        this.$route.path === item.path ||
        (this.$route.path === "/home" && item.path === "/")
      ) {
        return;
      }
      this.$router.push(item.path);
      this.$store.commit('tab/setTabsList',[parentItem,item])
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    }
  },
  computed: {
    getSelected(){
      return this.$route.path
    },
    noChildren() {
      return this.menuData.filter(item => !item.children);
    },
    hasChildren() {
      return this.menuData.filter(item => item.children);
    },
    isCollapse() {
      return this.$store.state.tab.isCollapse;
    }
  }
};
</script>

<style lang="less" scoped>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
.el-menu {
  height: 100vh;
  border-right: none;
  h3 {
    color: #fff;
    text-align: center;
    line-height: 48px;
    font-size: 16px;
    font-weight: 400;
  }
}
.el-submenu .el-menu-item {
  background-color: #404040 !important; /* 二级菜单子项背景色 */
}
</style>
